import { useEffect } from "react";
import { connect } from "react-redux";
import "./index.scss";

function Global(props) {
    const { isLogin } = props;
    useEffect(() => {
        if (!isLogin) {
            getUserInfo();
        }
    }, [isLogin]);

    const login = () => {
        const { app } = window as any;
        var param: any = {};
        param.isReturnPage = false;
        if (typeof app.link.goLogin == "function") {
            app.link.goLogin(
                function (res) {
                    alert(res.cityName);
                },
                function (error) {
                    console.log(error);
                },
                param
            );
        }
    };

    const getUserInfo = () => {
        setTimeout(function () {
            const { app } = window as any;
            if (typeof app?.link?.getLoginInfo == "function") {
                app.link.getLoginInfo(
                    function (res) {
                        var userinfo = res;
                        let str = "";
                        Object.keys(userinfo).forEach((it) => {
                            str += it + ",\n";
                        });
                        // @ts-ignore
                        var encrypt = new JSEncrypt();
                        // @ts-ignore
                        encrypt.setPrivateKey(keyUtil.getPrivateKey());
                        var userId = encrypt.decrypt(userinfo.userId); //用户id
                        var userToken = encrypt.decrypt(userinfo.USER_TOKEN); //用户token
                        var userIdCard = encrypt.decrypt(userinfo.cardNum); //证件号码
                        var userName = encrypt.decrypt(userinfo.name); //用户姓名
                        var userMobile = encrypt.decrypt(userinfo.user_mobile); //用户姓名
                        props.dispatch({
                            type: "user_updateState",
                            data: {
                                userId,
                                userName,
                                phone: userMobile,
                                cardNo: userIdCard,
                                userToken,
                            },
                        });
                    },
                    function () {
                        login();
                    }
                );
            }
        }, 300);
    };

    return null;
}

export default connect(({ user }) => {
    const { isLogin } = user;
    return {
        isLogin,
    };
})(Global);
